<script setup lang="ts">
import { ref, h, reactive } from "vue";
import { useColumns } from "./columns";
import { IconifyIconOnline } from "@/components/ReIcon";
import { PlusDialogForm } from "plus-pro-components";
import {
  createDeliveryPerson,
  updateDeliveryPerson,
  deleteDeliveryPerson
} from "@/api/delivery-person";
import type {
  PlusColumn,
  FieldValues,
  PlusFormInstance
} from "plus-pro-components";
import { message } from "@/utils/message";
import { dayjs, ElImage, ElInput, ElTag, FormItemRule } from "element-plus";

const SERVER_URL = import.meta.env.VITE_SERVER_URL;

const tableRef = ref();

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  searchText,
  onSizeChange,
  onCurrentChange,
  refresh,
  search
} = useColumns({
  onEdit: (row, index) => {
    formData.value = {
      id: row.id,
      name: row.name,
      phone: row.phone
    };

    formVisible.value = true;
  },
  onDelete: async (row, index) => {
    try {
      await deleteDeliveryPerson(row.id);
      message("删除成功", { type: "success" });
      refresh();
    } catch (e) {
      if (e.response.data && e.response.data.message) {
        message(e.response.data.message, { type: "error" });
      } else {
        message("删除失败", { type: "error" });
      }
      console.log(e);
    }
  }
});

const formRules: Record<string, FormItemRule[]> = {
  name: [
    {
      required: true,
      message: "请输入名称"
    }
  ],
  phone: [
    {
      required: true,
      message: "请输入电话号码",
      trigger: "blur"
    },
    {
      validator: (rule, value, callback) => {
        const phoneRegex =
          /^0?(13[0-9]|14[57]|15[0-35-9]|17[0678]|18[0-9])[0-9]{8}$/;

        if (!value) {
          callback(new Error("请输入电话号码"));
        } else if (!phoneRegex.test(value)) {
          callback(new Error("电话号码格式不正确"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

const state = reactive({
  submitting: false
});

const formColumns: PlusColumn[] = [
  {
    label: "姓名",
    prop: "name",
    valueType: "input"
  },
  {
    label: "电话",
    prop: "phone",
    valueType: "input"
  }
];
const formVisible = ref(false);
const formData = ref<FieldValues>({});

const handleNew = () => {
  formData.value = {};
  formVisible.value = true;
};

const handleConfirm = async e => {
  try {
    state.submitting = true;

    if (e.id) {
      await updateDeliveryPerson(e);
    } else {
      await createDeliveryPerson(e);
    }

    message("保存成功", { type: "success" });
    formVisible.value = false;
    refresh();
  } catch (e) {
    if (e.response.data && e.response.data.message) {
      message(e.response.data.message, { type: "error" });
    } else {
      message("保存失败", { type: "error" });
    }
    console.log(e);
  } finally {
    state.submitting = false;
  }
};

const handleSearch = e => {
  search();
};
</script>
<template>
  <div>
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span>配送员管理</span>

          <el-space>
            <el-input
              v-model="searchText"
              style="width: 240px"
              clearable
              placeholder="请输入姓名"
              @change="handleSearch"
            >
              <template #append>
                <IconifyIconOnline icon="ep:search" />
              </template>
            </el-input>
            <el-button type="primary" @click="handleNew">
              <template #icon>
                <IconifyIconOnline icon="ep:plus" />
              </template>
              新增
            </el-button>
          </el-space>
        </div>
      </template>
      <pure-table
        ref="tableRef"
        border
        adaptive
        :adaptiveConfig="adaptiveConfig"
        row-key="id"
        alignWhole="center"
        showOverflowTooltip
        :loading="loading"
        :loading-config="loadingConfig"
        :data="dataList"
        :columns="columns"
        :pagination="pagination"
        @page-size-change="onSizeChange"
        @page-current-change="onCurrentChange"
      />
    </el-card>
    <PlusDialogForm
      v-model:visible="formVisible"
      v-model="formData"
      :destroy-on-close="true"
      :title="formData.id ? '编辑配送员' : '添加配送员'"
      width="480px"
      :form="{
        columns: formColumns,
        rules: formRules,
        labelPosition: 'top'
      }"
      :confirmLoading="state.submitting"
      @confirm="handleConfirm"
    />
  </div>
</template>
